package com.gy.niuer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.niuer.domain.Doctor;
import com.gy.niuer.mapper.DepartmentMapper;
import com.gy.niuer.service.DoctorService;
import com.gy.niuer.mapper.DoctorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
*
*/
@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor>
implements DoctorService{

    @Autowired
    DoctorMapper doctorMapper;

    @Autowired
    DepartmentMapper departmentMapper;


    @Override
    public List<Doctor> getDoctorByDepartment(int id) {

        return doctorMapper.getByDepartment(id);
    }

    @Override
    public boolean thumbsOneDoctor(int id,int patientId) {

        Doctor doctor = doctorMapper.selectOneById(id);

        boolean isYet = true;  //记录该医生是否还能被该用户点赞

        if(doctor.getThumbsId() != null){
            String[] ids = doctor.getThumbsId().split(",");

            for (String s:ids) {
                if(String.valueOf(patientId).equals(s)){
                    isYet = false;
                }
            }
        }

        if(isYet){
            doctorMapper.updateThumbs(id); //点赞数+1

            //将点赞用户的id记入
            if(doctor.getThumbsId() == null){
                doctor.setThumbsId(patientId + "");
                doctorMapper.updateThumbsIdById(patientId + "",id);
            }else {
                doctor.setThumbsId(doctor.getThumbsId() + "," + id);
                doctorMapper.updateThumbsIdById(doctor.getThumbsId() + "," + patientId,id);
            }

            return true;
        }

        return false;
    }

    //获取通过点赞数排序的医生集合
    @Override
    public List<Doctor> getSortedDoctor() {

        List<Doctor> doctors = doctorMapper.selectAllDoctor();

        doctors.sort(Comparator.comparing(Doctor::getThumbsCount).reversed());//按点赞数对医生进行排序

        List<Doctor> doctors1 = doctors.subList(0, 10);//取前10

        return doctors1;
    }

    @Override
    public boolean isThumbed(String thumbsId, int patient) {
        if(thumbsId == null){
            return true;
        }else{
            String[] split = thumbsId.split(",");
            for (String s: split) {
                if(s.equals(patient + "")){
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public boolean addDoctor(Doctor doctor) {
         doctorMapper.addAll(doctor);
         return true;
    }

    @Override
    public List<Doctor> getAllDoctor() {

        List<Doctor> doctors = doctorMapper.selectAll();
        return doctors;
    }
}
